#!/usr/bin/perl -w # for syntax highlighting
# CSS-V1

# Take all the args and update portal ... and then
# redirect to page in the LP parameter.
use gri_secmgr qw(get_cookie_value redirect_header);
use gri_user_alert_config;
use gri_portal_config;

sub mm_form_delete_report_process {
	my $report_name=$::PARAM{report_name};
	my $report_filename=hex_to_string($report_name);
	my $portals_dir=$::GRI_FRONTEND->get_global_directory("portals");
	my $reports_dir=$::GRI_FRONTEND->get_global_directory("reports");
	my $serror=undef;
	my $error=undef;
	my $dfd;
	if(! -w $portals_dir) {
		$serror="Error Removing Existing Report";
		$error="Unable to write to the portals directory: $portals_dir.";
	}
	if(! -w $reports_dir) {
		$serror="Error Removing Existing Report";
		$error="Unable to write to the reports directory: $portals_dir.";
	}
	if(! $error && !opendir($dfd,$portals_dir)) {
		$serror="Error Removing Existing Report";
		$error="Unable to open the portals directory: $portals_dir - $!";
	}
	if(! $error) {
		my $cfile;
		while($cfile=readdir($dfd)) {
			next if ! -f "$portals_dir/$cfile";
			next if ! -r "$portals_dir/$cfile";
			my $portal_cfg=new gri_portal_config("$portals_dir/$cfile");
			if(!defined($portal_cfg)) {
				$serror="Error Removing Existing Report";
				$error="Unable to read portal information in file '$portals_dir/$cfile'.";
				last;
			}
			my $reps=$portal_cfg->get_reports();
			my @F=split(/,/,$reps);
			my @F2=grep {$_ ne $report_filename} @F;
			if(@F != @F2) {
				$portal_cfg->set_reports(join(",",@F2));
				my ($rc,$err)=$portal_cfg->write_file();
				if($rc==0) {
					$serror="Error Removing Existing Report";
					$error=$err;
					last;
				}
			}
		}
		closedir($dfd);
	}
	if(! $error && !unlink("$reports_dir/$report_filename.xml")) {
		$serror="Error Removing Existing Report";
		$error="Specified report filename ['$reports_dir/$report_filename.xml']could not be deleted - $!";
	}
	if($error) {
		my $link=link_to_str("","","show_generic_error","?serror=".string_to_hex($serror).",error=".string_to_hex($error));
		if(!exists($::PARAM{lp})) {
			# We need to encode the current data for repopulation into the form!
			$link.=",previouspage=admin_page";
		}
		redirect_header(path => $link);
		exit;
	}

	my $link=link_to_str("","","/admin_page","");
	redirect_header(path => $link);
	exit;
}

